<template>
  <div id="teamAddPage">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          clearable
          v-model="addTeamData.name"
          name="name"
          label="队伍名"
          placeholder="请输入队伍名"
          :rules="[{ validator: validatorMessageName }]"
        />
        <van-field
          clearable
          v-model="addTeamData.description"
          rows="4"
          autosize
          label="队伍描述"
          type="textarea"
          placeholder="请输入队伍描述"
          maxlength="40"
          show-word-limit
          :rules="[{ validator: validatorMessageDesc }]"
        />
        <van-cell
          title="过期时间:"
          :value="date == '' ? '点击选择过期时间' : date"
          @click="Onclick"
        />
        <van-calendar
          v-model:show="showPicker"
          :min-date="minDate"
          :max-date="maxDate"
          :show-confirm="false"
          @confirm="onConfirm"
          ><template #title>
            <span class="vip">开通VIP可延长队伍过期时间</span>
          </template></van-calendar
        >
        <van-field clearable name="stepper" label="最大人数">
          <template #input>
            <van-stepper v-model="addTeamData.maxNum" max="10" min="3" />
          </template>
        </van-field>
        <van-field clearable name="radio" label="队伍状态">
          <template #input>
            <van-radio-group
              v-model="addTeamData.status"
              direction="horizontal"
            >
              <van-radio name="0">公开</van-radio>
              <van-radio name="1">私有</van-radio>
              <van-radio name="2">加密</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          clearable
          v-if="Number(addTeamData.status) === 2"
          v-model="addTeamData.password"
          type="password"
          name="password"
          label="密码"
          placeholder="请输入队伍密码"
          :rules="[{ validator: validatorMessagePassword }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          保存
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import moment from "moment";
import myAxios from "../plugins/myAxios";
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { showSuccessToast, showFailToast, showConfirmDialog } from "vant";

const showPicker = ref(false); // 展示日期选择器
const day = new Date(); //当前时间
const minDate = new Date(); //最大时间
const maxDate = new Date(); //最小时间
const Onclick = () => {
  showPicker.value = true; // 展示日期选择器
  minDate.setDate(day.getDate() + 1); //设置最小日期
  //设置最大日期
  const now = moment().add(14, "days");
  maxDate.setFullYear(now.year());
  maxDate.setMonth(now.month());
  maxDate.setDate(now.date());
};

const date = ref(""); //展示过期时间
const onConfirm = (value: any) => {
  showPicker.value = false;
  date.value = formatDate(value); //将选中的日期格式化做展示
  addTeamData.value.expireTime = value;
};
const formatDate = (date: Date) =>
  `${date.getMonth() + 1}月${date.getDate()}日-00:00:00`;

//表单校验
const special = /[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/;
const validatorMessageName = (val: string) => {
  if (val.trim() == "") {
    return "队伍名不能为空";
  }
  if (val.length < 2 || val.length > 6) {
    return "队伍名长度必须在2-6位之间";
  }
  if (special.test(val)) {
    return "队伍名不能包含特殊字符";
  }
};
const validatorMessageDesc = (val: string) => {
  if (val.trim() == "") {
    return "队伍描述不能为空";
  }
  if (val.length < 6 || val.length > 50) {
    return "队伍描述的长度必须在6-40位之间";
  }
  if (special.test(val)) {
    return "队伍描述不能包含特殊字符";
  }
};
const validatorMessagePassword = (val: string) => {
  if (val.trim() == "") {
    return "密码不能为空";
  }
  if (val.length < 8 || val.length > 16) {
    return "密码长度必须在8-16位之间";
  }
  if (!val.match(/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/)) {
    return "密码必须只包含数字和字母";
  }
  if (special.test(val)) {
    return "密码不能包含特殊字符";
  }
};

const route = useRoute();
const id = route.query.id; //队伍id
const userId = Number(route.query.userId);
const router = useRouter();
const addTeamData = ref({}); // 用户填写的表单数据
const onSubmit = async () => {
  showConfirmDialog({
    message: "确认你的保存吗",
  })
    .then(async () => {
      const postData = {
        ...addTeamData.value,
        status: Number(addTeamData.value.status),
      };
      if (id != "0") {
        const res = await myAxios.post("/team/update", postData);
        if (res.code === 0 && res.data) {
          router.push({
            path: "/user/team",
            replace: true,
            query: {
              userId: userId,
              currentUserId: 0,
            },
          });
          showSuccessToast("小智暖心提醒:修改成功");
        } else {
          showFailToast(`小智遗憾告知:${res.message}`);
        }
      } else {
        const res = await myAxios.post("/team/add", postData);
        if (res?.code === 0) {
          router.push({
            path: "/user/team",
            replace: true,
            query: {
              userId: userId,
              currentUserId: userId,
            },
          });
          showSuccessToast("小智暖心提醒:开团成功");
        } else {
          showFailToast(
            `小智遗憾告知:${
              res.message ?? "与服务器失联 请到上一个页面刷新重试"
            }`
          );
        }
      }
    })
    .catch(() => {});
};

// 获取队伍的详细信息
onMounted(async () => {
  if (id != "0") {
    const res = await myAxios.get("/team/get", {
      params: {
        id,
      },
    });
    if (res.code === 0) {
      addTeamData.value = res.data;
      date.value = formatDate(new Date(addTeamData.value.expireTime));
    } else {
      showFailToast("小智遗憾告知:队伍加载失败");
    }
  }
});
</script>

<style scoped>
@import "../assets/css/public.css";
</style>
